/**
 * Created by tangting on 2017/10/26.
 */

import Vue from 'vue';
import WebBox from '../../component/WebBox/WebBox';
import commonService from '../../common/commonService';
import Loading from '../../../grsc-base/component/Loading.vue';
import Validator from '../../../grsc-base/component/Validator/main';
import RegisterSuccess from '../../component/RegisterSuccess.vue';
import {REG_EMAIL, REG_EMAIL_PHONE, REG_LOGPWD, REG_PAYPWD} from '../../../grsc-base/common/constants';
import tpl from './tpl.html';

export default Vue.extend({
    template: tpl,
    components: {
        WebBox,
        Loading,
        Validator,
        RegisterSuccess
    },
    data() {
        return {
            isLoading: false,

            randomKey: '',
            imgCodeSrc: '',

            // actAmount: 0,
            assetList:[],
            returnRandomkey: '',

            form: {
                email: '',
                identifyingPic: '',
                identifyingCode: '',
                sendingCode: false,
                codeBtnText: this.$t('common.sendEmail'), // 发送验证码
                codeLock: false,
            },
            rules: {
                email: {
                    tip: "",
                    required: true,
                    requiredTip: '請輸入賬戶地址',
                    pattern: REG_EMAIL_PHONE,
                    patternTip: window.CODE.EMAIL_PHONE[this.$i18n.locale]
                },
                identifyingPic: {
                    required: true,
                    requiredTip: this.$t('common.captchaRequireTip')
                },
                identifyingCode: {
                    required: true,
                    requiredTip: '請輸入驗證碼',
                    pattern: '\\d{6}',
                    patternTip: this.$t('common.IncorrectverifyCodeTip')
                },
            },

            pwdFrom: {
                email: '',
                identifyingPic: '',
                identifyingCode: '',
                sendingCode: false,
                codeBtnText: this.$t('common.sendEmail'), // 发送验证码
                codeLock: false,
                logPsd: '',
                logConfirmPsd: '',
                payPsd: '',
                payConfirmPsd: ''
            },
            pwdRules: {
                email: {
                    tip: "",
                    required: true,
                    requiredTip: this.$t('common.emailRequireTip'),
                    pattern: REG_EMAIL,
                    patternTip: window.CODE.EMAIL[this.$i18n.locale]
                },
                identifyingPic: {
                    required: true,
                    requiredTip: this.$t('common.captchaRequireTip')
                },
                identifyingCode: {
                    required: true,
                    requiredTip: '請輸入驗證碼',
                    pattern: '\\d{6}',
                    patternTip: this.$t('common.IncorrectverifyCodeTip')
                },
                logPsd: {
                    tip: '',
                    required: true,
                    requiredTip: this.$t('common.loginPassRequireTip'),
                    minlength: 6,
                    minlengthTip: this.$t('common.ruleLoginPassLength'),
                    maxlength: 20,
                    maxlengthTip: this.$t('common.ruleLoginPassLength'),
                    pattern: REG_LOGPWD,
                    patternTip: this.$t('common.ruleLoginPassPattern')
                },
                logConfirmPsd: {
                    required: true,
                    requiredTip: this.$t('common.repeatPassRequireTip'),
                    equalTo: 'logPsd',
                    equalToTip: this.$t('common.passEqualTip')
                },
                payPsd: {
                    tip: '',
                    minlength: 8,
                    minlengthTip: this.$t('common.ruleAssetPassLength'),
                    maxlength: 20,
                    maxlengthTip: this.$t('common.ruleAssetPassLength'),
                    pattern: REG_PAYPWD,
                    patternTip: this.$t('common.ruleAssetPassPattern'),
                    required: true,
                    requiredTip: this.$t('common.assetPassRequireTip')
                },
                payConfirmPsd: {
                    required: true,
                    requiredTip: this.$t('common.repeatPassRequireTip'),
                    // requiredTip: '請再次輸入密碼',
                    equalTo: 'payPsd',
                    equalToTip: this.$t('common.passEqualTip')
                }
            },
            isRequesting: false, // 首次证证提交等待
            isRegisting: false, // 注册提交等待
            count: 5, // 认证为完成倒计时
            leftSeconds: 7,  // 全部成功后跳转到YourDax倒计时

            isVerify: true,
            verifySuccess : false,
            isRegister: false,
            allSuccess: false
        }
    },
    created() {
        this.changeImgCode();
    },
    watch: {

    },
    methods: {
        /**
         * 改变图形验证码
         */
        changeImgCode() {
            this.randomKey = new Date().getTime();
            commonService.getCode({
                randomKey: this.randomKey
            }).done(rep => {
                this.imgCodeSrc = rep;
            });
        },

        /**
         * 点击获取短信验证码
         */
        sendCodeVerify(){
            this.rules.email.$check();
            if (this.form.identifyingPic === '') {
                this.rules.identifyingPic.$setError(this.$t('common.captchaRequireTip'));
            }
            if (this.rules.email.$valid === false || this.form.identifyingPic === '') {
                return;
            }
            let that = this;
            let loopTimeId = null;
            let counts = 60;

            //登录后发送验证码不需要手机号信息
            this.form.sendingCode = true;
            commonService.sendCode({
                sendAccount: this.form.email
            }, {
                'captchar-code': this.form.identifyingPic,
                'captchar-no': this.randomKey
            }).done((rep) => {
                if (rep.code == window.CODE.SUCCESS) {
                    this.form.codeLock = true;//获取验证码锁定 true：正在获取验证码，不可点击   false：可以点击
                    this.rules.identifyingCode.$setRight('驗證碼已發送');
                    send();
                    loopTimeId = setInterval(function () {
                        send();
                    }, 1000);
                } else if (rep.code === window.CODE.EMAIL_PHONE.CODE) {
                    this.rules.email.$setError(window.CODE.EMAIL_PHONE[this.$i18n.locale]);
                } else if (rep.code === window.CODE.CAPTCHA.CODE) {
                    this.changeImgCode();
                    this.rules.identifyingPic.$setError(window.CODE.CAPTCHA[this.$i18n.locale]);
                } else if (rep.code === window.CODE.IDENTIFY_HAS_SEND.CODE) {
                    this.rules.identifyingCode.$setError('驗證碼已發送');
                } else {
                    window.error(rep.msg);
                }
            }).fail((rep) => {
                window.error(rep.msg);
            }).always(()=>{
                this.form.sendingCode = false;
            });

            function send() {
                if (counts > 0) {
                    that.form.codeBtnText = counts + 's';
                    counts--;
                } else {
                    clearInterval(loopTimeId);
                    that.form.codeBtnText = '重新獲取';
                    that.form.codeLock = false;
                }
            }

        },

        sendCodeRegister(){
            this.pwdRules.email.$check();
            if (this.pwdFrom.identifyingPic === '') {
                this.pwdRules.identifyingPic.$setError(this.$t('common.captchaRequireTip'));
            }
            if (this.pwdRules.email.$valid === false || this.pwdFrom.identifyingPic === '') {
                return;
            }
            let that = this;
            let loopTimeId = null;
            let counts = 60;

            //登录后发送验证码不需要手机号信息
            this.pwdFrom.sendingCode = true;
            commonService.sendCode({
                // sendType: 'EMAIL',
                sendAccount: this.pwdFrom.email
            }, {
                'captchar-code': this.pwdFrom.identifyingPic,
                'captchar-no': this.randomKey
            }).done((rep) => {
                if (rep.code == window.CODE.SUCCESS) {
                    this.pwdFrom.codeLock = true;//获取验证码锁定 true：正在获取验证码，不可点击   false：可以点击
                    this.pwdRules.identifyingCode.$setRight('驗證碼已發送');
                    send();
                    loopTimeId = setInterval(function () {
                        send();
                    }, 1000);
                } else if (rep.code === window.CODE.EMAIL.CODE) {
                    this.pwdRules.email.$setError(window.CODE.EMAIL[this.$i18n.locale]);
                } else if (rep.code === window.CODE.CAPTCHA.CODE) {
                    this.changeImgCode();
                    this.pwdRules.identifyingPic.$setError(window.CODE.CAPTCHA[this.$i18n.locale]);
                } else if (rep.code === window.CODE.IDENTIFY_HAS_SEND.CODE) {
                    this.pwdRules.identifyingCode.$setError('驗證碼已發送');
                } else {
                    window.error(rep.msg);
                }
            }).fail((rep) => {
                window.error(rep.msg);
            }).always(()=>{
                this.pwdFrom.sendingCode = false;
            });

            function send() {
                if (counts > 0) {
                    that.pwdFrom.codeBtnText = counts + 's';
                    counts--;
                } else {
                    clearInterval(loopTimeId);
                    that.pwdFrom.codeBtnText = '重新獲取';
                    that.pwdFrom.codeLock = false;
                }
            }

        },

        /**
         * 首次账号验证
         */
        submit() {
            if (this.rules.$checkAll() === false) {
                return;
            }
            this.isRequesting = true;
            commonService.queryJubiUserMsg({},{
                'account-no': this.form.email,
                'captchar-code': this.form.identifyingPic,
                'captchar-no': this.randomKey,
                'service-code': this.form.identifyingCode
            }).done(rep => {
                if(rep.code === window.CODE.SUCCESS){
                    this.verifySuccess = true;
                    // this.actAmount = rep.data.amount;
                    this.assetList = rep.data.assetList;
                    this.returnRandomkey = rep.data.randomkey;
                    this._downTime();
                }else {
                    if (rep.code === window.CODE.IDENTIFY.CODE) {
                        this.changeImgCode();
                        this.rules.identifyingCode.$setError(window.CODE.IDENTIFY[this.$i18n.locale]);
                    } else if (rep.code === window.CODE.IDENTIFY_INVALID.CODE) {
                        this.changeImgCode();
                        this.rules.identifyingCode.$setError(window.CODE.IDENTIFY_INVALID[this.$i18n.locale]);
                    } else if (rep.code === window.CODE.HAS_REGISTER.CODE) {
                        this.changeImgCode();
                        this.rules.email.$setError(window.CODE.HAS_REGISTER[this.$i18n.locale]);
                    } else {
                        window.error(rep.msg);
                    }
                }
            }).always(rep => {
                this.isRequesting = false;
            });
        },

        /**
         * 验证注册密码
         */
        checkPsd(){
            this.pwdRules.logPsd.tip = this.$t('common.ruleLoginPassLength');
        },
        checkPsdBlur() {
            this.pwdRules.logPsd.tip = '';
        },
        /**
         * 验证支付密码
         */
        checkPayPsd() {
            this.pwdRules.payPsd.tip = this.$t('common.ruleAssetPassLength');
        },

        checkPayPsdBlur() {
            this.pwdRules.payPsd.tip = '';
            this.tmpPsdVal = $.trim($(this.$refs.payPsd).val());
        },

        /**
         * 注册验证
         */
        totalSubmit() {
            if (this.pwdRules.$checkAll() === false) {
                return;
            }

            let params = {
                'jubiAccount': this.form.email,
                'randomkey': this.returnRandomkey,
                'loginPassword': this.pwdFrom.logPsd,
                'payPassword': this.pwdFrom.payPsd
            };

            let header = {
                'account-no': this.pwdFrom.email,
                'captchar-code': this.pwdFrom.identifyingPic,
                'captchar-no': this.randomKey,
                'service-code': this.pwdFrom.identifyingCode
            };

            this.isRegisting = true;
            commonService.registerJubiUser(params, header).done((rep)=> {
                if (rep.code === window.CODE.SUCCESS) {
                    this.allSuccess = true;
                    this.isVerify = false;
                    this.isRegister = false;
                    let timer = setInterval(()=> {
                        this.leftSeconds--;
                        if (this.leftSeconds <= 1) {
                            clearInterval(timer);
                            location.href = 'https://www.yourdax.com/hk/login.html';
                        }
                    }, 1000)
                } else {
                    if (rep.code === window.CODE.IDENTIFY.CODE) {
                        this.changeImgCode();
                        this.pwdRules.identifyingCode.$setError(window.CODE.IDENTIFY[this.$i18n.locale]);
                    } else if (rep.code === window.CODE.IDENTIFY_INVALID.CODE) {
                        this.changeImgCode();
                        this.pwdRules.identifyingCode.$setError(window.CODE.IDENTIFY_INVALID[this.$i18n.locale]);
                    } else if (rep.code === window.CODE.HAS_REGISTER.CODE) {
                        this.changeImgCode();
                        this.pwdRules.email.$setError(window.CODE.HAS_REGISTER[this.$i18n.locale]);
                        setTimeout(function(){
                            location.href = 'https://www.yourdax.com/hk/login.html';
                        },3000)
                    } else {
                        window.error(rep.msg);
                    }
                }
            }).always(rep => {
                this.isRegisting = false;
            });
        },

        /**
         * 认证成功倒计时
         */
        _downTime() {
            let timer = setInterval(()=> {
                this.count--;
                if (this.count <= 0) {
                    clearInterval(timer);
                    this.isVerify = false;
                    this.isRegister = true;
                    this.changeImgCode();
                }
            }, 1000)
        }
    }
});
